package org.imaginedays.androidall.widget;

import org.imaginedays.androidall.R;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
 * 带有清除按钮的 EditText
 * 
 * @author imaginedays
 * 
 */
public class CleanBtnEditText extends EditText {

	private Drawable imgCloseButton = getResources().getDrawable(
			R.drawable.btn_close);

	public CleanBtnEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public CleanBtnEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public CleanBtnEditText(Context context) {
		super(context);
		init();
	}

	void init() {
		// Set bounds of the Clear button so it will look ok
		imgCloseButton.setBounds(0, 0, imgCloseButton.getIntrinsicWidth(),
				imgCloseButton.getIntrinsicHeight());

		// There may be initial text in the field, so we may need to display the
		// button
		handleClearButton();

		// if the Close image is displayed and the user remove his finger from
		// the button, clear it. Otherwise do nothing   处理 按钮点touch事件
		this.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				CleanBtnEditText ce = CleanBtnEditText.this;
				if (ce.getCompoundDrawables()[2] == null)//如果右边的清除图片按钮不存在的话，不处理
					return false;

				if (event.getAction() != MotionEvent.ACTION_UP)//如果没有松开按钮的话 不处理
					return false;

				if (event.getX() > ce.getWidth() - ce.getPaddingRight()
						- imgCloseButton.getIntrinsicWidth()) {
					ce.setText("");
					ce.handleClearButton();
				}

				return false;
			}
		});

		this.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				CleanBtnEditText.this.handleClearButton();

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void handleClearButton() {
		if (this.getText().toString().equals("")) {
		
			// remove clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0],
					this.getCompoundDrawables()[1], null,
					this.getCompoundDrawables()[3]);
		} else {
			// add the clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0],
					this.getCompoundDrawables()[1], imgCloseButton,
					this.getCompoundDrawables()[3]);
		}
	}

}
